package com.xinxin.datastructure.utils;

import java.math.BigDecimal;
import java.util.Random;

/**
 * 工具类
 *
 * @author 史鑫鑫
 * @date Created in 2019/5/24 1:07
 */
public class DataStructureUtil {
    private static final Integer MIN_NUM = 12;
    private static final Integer MAX_NUM = 20;

    /**
     * 随机获取长度为12~20的大小写字母混杂的“单词”
     */
    public static String randomWord() {
        return randomWord(MIN_NUM, MAX_NUM);
    }

    /**
     * 随机获取长度为m~m的大小写字母混杂的“单词”
     */
    public static String randomWord(int m, int n) {
        Random random = new Random();
        // 12~20长度，包含12及20
        int length = m + random.nextInt(n - m + 1);
        StringBuilder word = new StringBuilder();
        for (int i = 0; i < length; i++) {
            word.append(randomChar());
        }
        return word.toString();
    }

    /**
     * 随机获取'a'~'z' 和 'A'~ 'Z'中的任一字符
     * 'A'~ 'Z'对应ASCII值：65~90
     * 'a'~'z'对应ASCII值：97~122
     *
     * @return 随机产生的字母
     */
    private static char randomCharacter() {
        Random random = new Random();
        int bt = random.nextInt(95);
        int resultBt = 33 + bt;
        return (char) resultBt;
    }

    /**
     * 随机获取'a'~'z' 和 'A'~ 'Z'中的任一字符
     * 'A'~ 'Z'对应ASCII值：65~90
     * 'a'~'z'对应ASCII值：97~122
     *
     * @return 随机产生的字母
     */
    private static char randomChar() {
        Random random = new Random();
        // 0小写字母1大写字母
        int flag = random.nextInt(2);
        // 0 <= bt < 26
        int bt = random.nextInt(26);
        int resultBt = bt + flag == 1 ? 65 : 97;
        return (char) resultBt;
    }

    /**
     * 判断一个整数是否是2的n次方
     *
     * @param num 整数
     * @return 是否为2的n次方
     */
    public static boolean powerOf2(int num) {
        return num > 0 && (num & (num - 1)) == 0;
    }

    /**
     * 纳秒转秒
     *
     * @param second 秒
     * @return 纳秒
     */
    public static BigDecimal getSecondFromNanosecond(long second) {
        return BigDecimal.valueOf(second / 1000000000.0);
    }
}
